package com.thinkwide.data.core;

import com.thinkwide.data.debug.MFDebug;

import java.util.ArrayList;
import java.util.List;

public class MFStringKeyValue {
    private List<MFKeyValue> keys;

    public MFStringKeyValue() {
        keys = new ArrayList<MFKeyValue>();
    }

    public List<MFKeyValue> getKeys() {
        return keys;
    }

    public void clear() {
        keys.clear();
    }

    public void delete(String key) {
        for (MFKeyValue item : keys) {
            if (MFString.compareNoCase(key, item.getKey())) {
                keys.remove(key);
            }
        }
    }

    public void add(String key, String value) {
        keys.add(new MFKeyValue(key, value));
    }

    public boolean hasKey(String key) {
        for (MFKeyValue item : keys) {
            if (MFString.compareNoCase(key, item.getKey())) {
                return true;
            }
        }
        return false;
    }

    public String getValue(String key) {
        for (MFKeyValue item : keys) {
            if (MFString.compareNoCase(key, item.getKey())) {
                return item.getValue();
            }
        }
        return null;
    }

    public String toString() {
        String value = "";
        for (MFKeyValue item : keys) {
            value = value + item.getKey() + "=" + item.getValue() + MFString.NewLine;
        }

        return value;
    }

    public MFKeyValue findKey(String key) {
        for (MFKeyValue item : keys) {
            if (MFString.compareNoCase(key, item.getKey())) {
                return item;
            }
        }
        return null;
    }

    public void loadString(String values) {
        if (MFString.isNullOrEmpty(values)) return;

        String[] data = values.split(MFString.NewLine);
        keys.clear();
        for (String item : data) {
            if (MFString.notNullOrEmpty(item)) {
                String key = MFString.getStrName(item, "=");
                String value = MFString.getStrValue(item, "=");
                keys.add(new MFKeyValue(key, value));
            }
        }

        MFDebug.println(keys.toString());
    }
}
